/*
 * @Description:
 * @Version: 1.0.0
 * @Author: gyh
 * @Date: 2021-08-17 22:33:44
 * @LastEditors: gyh
 * @LastEditTime: 2021-08-17 22:34:28
 */
import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
import { getToken } from '@/utils/cookie'
import { ElMessage, ElLoading } from 'element-plus'

const dealStatus = (code: number = 0, msg: string = '') => {
  switch (code) {
    case 400:
      return ElMessage.warning(msg || '请求错误')
    case 401:
      return ElMessage.warning(msg || '很抱歉，您暂未授权，请重新登录')
    case 403:
      return ElMessage.warning(msg || '很抱歉，您无法访问该资源，可能是因为没有相应权限或者登录已失效')
    case 404:
      return ElMessage.warning(msg || '很抱歉，资源未找到')
    case 500:
      return ElMessage.warning(msg || '很抱歉，系统发生错误，请联系管理员')
    case 504:
      return ElMessage.warning(msg || '很抱歉，系统连接超时，请联系管理员')
    default:
      return ElMessage.warning(msg || '很抱歉，系统发生错误，请联系管理员')
  }
}

let loading: any = null // 加载动画
console.log(import.meta.env)
const service = axios.create({
  baseURL: '/api',
  timeout: 50000,
  // withCredentials: true, // 是否跨站点访问控制请求
})

service.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    const token = getToken()
    if (token) config.headers.Authorization = `Bearer ${token}`
    loading = ElLoading.service({
      text: '正在请求中...',
      body: false,
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.2)',
      customClass: 'custom-loading',
    })
    return config
  },
  error => {
    console.log(`request error: ${error}`) // for debug
    return Promise.reject(error)
  },
)

service.interceptors.response.use(
  (response: AxiosResponse) => {
    loading && loading.close()
    dealStatus(response.data.code, response.data.msg)
    return response
  },
  error => {
    console.log(`request error: ${error}`) // for debug
    loading && loading.close()
    dealStatus()
    return Promise.reject(error)
  },
)

export const get = (url: string, params: object) => {
  return new Promise((resolve, reject) => {
    service
      .get(url, {
        params,
      })
      .then(res => {
        resolve(res)
      })
      .catch(err => {
        reject(err)
      })
  })
}

export const post = (url: string, params: object) => {
  return new Promise((resolve, reject) => {
    service
      .post(url, params)
      .then(res => {
        resolve(res)
      })
      .catch(err => {
        reject(err)
      })
  })
}
